<template>
	<z-paging ref="paging" v-model="dataList" @query="queryList"
		:loading-more-custom-style="{ paddingBottom: 'env(safe-area-inset-bottom)' }">
		<template #top>
			<view class="zpagin_top">
				<nav-bar :iconLeft="true" />
				<view class="search">
					<custom-search v-model="queryParams.search" @search="refreshList" placeholder="请输入合同类型名称" />
					<uni-data-select v-model="queryParams.company" :localdata="company_list" placeholder="请选择所属租户"
						@change="refreshList" />
				</view>
				<dui-float-ball :pathUrl="`${pageUrl}/compile`" v-if="$hasPerm(['20401'])" />
			</view>
		</template>
		<up-swipe-action>
			<up-swipe-action-item v-for="item in dataList" :key="item.id"
				:name="JSON.stringify(swipeActPer(options, null)) + '&' + item.id + '&' + item.full_name"
				:options="swipeActPer(options, null)" :disabled="swipeActPer(options, null, 'disabled')" @click="action">
				<uni-card margin="0" spacing="0">
					<template v-slot:title>
						<uni-list>
							<uni-list-item :title="`登录账号：${item.username}`" thumbSize="lg">
								<template v-slot:footer>
									<view style="display: flex; align-items: center;">
										<up-tag size="mini" :text="status_list[item.if_open].text" plain plainFill
											:type="status_list[item.if_open].type" style="display: inline-block;" />
										<switch style="transform:scale(0.7)" :checked="Boolean(item.if_open)"
											@change="checkedChange($event, item.id)" v-if="$hasPerm(['901204'])" />
									</view>
								</template>
							</uni-list-item>
						</uni-list>
					</template>
					<view class="ctent">用户名：{{ item.full_name }}</view>
					<view class="ctent">角色：{{ item.role_permission_names }}</view>
					<view class="ctent">所属租户：{{ item.company_name }}</view>
					<view class="ctent">创建时间：{{ item.create_date }}</view>
					<view class="con" style="align-items: normal;">
						<view class="ctent" style="flex: none;">备注：</view>
						<view class="ctent">{{ item.desc }}</view>
					</view>
					<view class="con_button" v-if="$hasPerm(['50105'])" @click.stop="editPass(item.id)">重置密码
					</view>
				</uni-card>
			</up-swipe-action-item>
		</up-swipe-action>
		<template #bottom>
			<custom-popup :popupShow="show" mode="center" title="修改密码" @close="show = false" width="95%">
				<view class="popup_content">
					<uni-forms :model="formData" :rules="rules" ref="form" labelAlign="right" label-width="90px">
						<uni-forms-item label="新密码" name="newpassword1" required>
							<up-input v-model="formData.newpassword1" password clearable placeholder="请输入新登录密码" border="bottom" />
						</uni-forms-item>
						<uni-forms-item label="确认新密码" name="newpassword2" required>
							<up-input v-model="formData.newpassword2" password clearable placeholder="请再次输入新登录密码" border="bottom" />
						</uni-forms-item>
					</uni-forms>
					<view style="display: flex; gap: 20rpx; margin-left:auto;">
						<up-button text="取消" size="small" @click="show = false"></up-button>
						<up-button text="确定" size="small" type="primary" @click="confirm"></up-button>
					</view>
				</view>
			</custom-popup>
		</template>
	</z-paging>
</template>
<script setup>
import { ref, reactive } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import syAccountApi from '../../../api/system/sy_account'
import { swipeActPer } from '@/utils/permission' // 用防抖优化请求频率（下面给出）
import loginAPI from '../../../api/login'

const status_list = {
	0: { text: '禁用', type: 'error' },
	1: { text: '启用', type: 'success' }
}

//作用于新增或编辑后刷新页面数据
uni.$bus.useBusOn('de_list', refreshList);
onLoad(() => {
	get_company_list()
})

const options = [
	{
		text: '修改', per: '20402',
		style: {
			backgroundColor: '#0081ff'
		}
	}, {
		text: '删除', per: '20403',
		style: {
			backgroundColor: '#f56c6c'
		}
	}
];

//页面跳转路径
const pageUrl = '/views/system/sy_account';

const queryParams = reactive({
	search: '',
});
const paging = ref(null);
const dataList = ref([]);
function queryList(pageNo, pageSize) {
	const params = {
		page: pageNo,
		page_size: pageSize,
		...queryParams
	}
	syAccountApi.get_account(params).then((res) => {
		paging.value.complete(res.results);
	})
};

function editPass(id) {
	formData.account_id = id
	show.value = true
}

const show = ref(false)
const form = ref(null)
const formData = reactive({
	account_id: null,
	newpassword1: '',
	newpassword2: '',
});
const rules = {
	newpassword2: {
		rules: [{ required: true, errorMessage: '请输入密码', trigger: ['change'] },
		{
			validateFunction: (rule, value, data, callback) => {
				if (value !== data.newpassword1) {
					callback('两次密码输入不同')
				}
				return true
			}
		}
		]
	},
};
function confirm() {
	form.value.validate().then(() => {
		loginAPI.update_password(formData).then(res => {
			uni.$u.toast('修改成功')
		}).catch(err => {
			uni.$u.toast(err.detail)
		})
	})
};


//switch操作
function checkedChange(e, id) {
	const if_open = e.detail.value ? 1 : 0
	syAccountApi.patch_account({ if_open }, id).then(res => {
		uni.$u.toast(if_open ? '启用成功' : '禁用成功')
		setTimeout(() => {
			refreshList();
		}, 500)
	})
};

//滑动操作按钮
function action(v) {
	const options = JSON.parse(v.name.split("&")[0])
	const id = v.name.split("&")[1]
	const delName = v.name.split("&")[2]
	const index = v.index
	if (options[index].text == '修改') {
		uni.navigateTo({
			url: `${pageUrl}/compile?type=edit&id=${id}`
		})
	}
	if (options[index].text == '删除') {
		delete_type(id, delName)
	}
};

const company_list = ref([])
function get_company_list() {
	syAccountApi.get_company({ page: 1, page_size: 99999 }).then((res) => {
		company_list.value = res.results.map(v => ({
			text: v.name, value: v.id
		}))
	})
}

//删除操作
function delete_type(id, delName) {
	uni.showModal({
		title: '提示',
		content: `确认要删除：【${delName}】的账号吗？`,
		success: (res) => {
			if (res.confirm) {
				syAccountApi.delete_account(id).then((res) => {
					uni.$u.toast('删除成功')
					setTimeout(() => {
						refreshList();
					}, 500)
				})
			}
		}
	});
};

//编辑跳转刷新
function refreshList() {
	paging.value.reload();
};
</script>

<style lang="scss">
.popup_content {
	background-color: #fff;
	padding: 20rpx 30rpx;
}
</style>